import type { Env } from '../types';
import { handleStaticFileRequest } from './handlers/staticHandler';
import { handleTextApiRequest } from './handlers/textHandler';
import { handleFileApiRequest } from './handlers/fileHandler';
import { handleFrontendRequest } from './handlers/frontendHandler';
import { handleOptionsRequest, addCorsHeaders } from '../utils/corsHandler';

export async function handleRequest(request: Request, env: Env): Promise<Response> {
  // 处理OPTIONS预检请求
  if (request.method === 'OPTIONS') {
    return handleOptionsRequest(request);
  }

  const url = new URL(request.url);
  const path = url.pathname;
  let response: Response;

  // 处理静态文件
  if (path.startsWith('/static/')) {
    response = await handleStaticFileRequest(request, url, env);
  }
  // 处理API请求
  else if (path.startsWith('/api/')) {
    // 文本API
    if (path.startsWith('/api/text/')) {
      response = await handleTextApiRequest(request, url, env);
    }
    // 文件API
    else if (path.startsWith('/api/file/')) {
      response = await handleFileApiRequest(request, url, env);
    }
    else {
      response = new Response('API not found', { status: 404 });
    }
  }
  // 处理前端路由
  else {
    response = await handleFrontendRequest(request, url, env);
  }

  // 添加CORS响应头
  return addCorsHeaders(response, request);
}